// pages/data/data.js
var wxCharts = require('./../../utils/wxcharts.js');
const aliSdk = require("./../../utils/aliIot-sdk.js");
var time = require('../../utils/util.js');
var {
  Client,
  Message
} = require('../../utils/paho-mqtt.js')
const app = getApp()
var lineChart = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    down_img: "../images/down.png",
    wendu_list: [],
    shidu_list: [],
    light_list: [],
    time_list: [],
    client: null,
    textcolor1: '#014f8e',
    textcolor2: '#bfbfbf',
    select: false,
    title: "光强",
    date: "1小时",
    select_date: false
  },
  onLoad: function (options) {
    var that = this;
    wx.getStorage({
      key: 'name',
      success: function (r) {
        console.log(r.data)
        that.setData({
          name: r.data,
        })
      }
    })
    // setInterval(function () {
    //   that.loadHistoryData();
    // }, 4000)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadHistoryData();
  },
  // 展示下拉列表的内容
  showMsg: function () {
    this.setData({
      select: !this.data.select
    })
  },
  showDate: function () {
    this.setData({
      select_date: !this.data.select_date
    })
  },

  //监听所选择内容
  mySelect: function (e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      title: name,
      select: false
    })
    if (name === "温度") {
      this.loadHistoryData();
      //lineChart.updateData();
      this.setData({
        textcolor1: '#bfbfbf',
        textcolor2: '#014f8e',
      })
      var x_data = this.data.time_list
      var y_data = this.data.wendu_list
      //绘制折线图
      this.OnWxChart(x_data, y_data, '温度')
    } else if (name === "湿度") {
      this.loadHistoryData();

      this.setData({
        textcolor1: '#bfbfbf',
        textcolor2: '#014f8e',
      })
      var x_data = this.data.time_list
      var y_data = this.data.shidu_list
      //绘制折线图
      this.OnWxChart(x_data, y_data, '湿度')
    } else {
      this.loadHistoryData();
      //lineChart.updateData();
      this.setData({
        textcolor1: '#014f8e',
        textcolor2: '#bfbfbf',
      })
      var x_data = this.data.time_list
      var y_data = this.data.light_list
      //绘制折线图
      this.OnWxChart(x_data, y_data, '光强')
    }

  },
  selectDate: function (e) {
    var date = e.currentTarget.dataset.item
    this.setData({
      date: date,
      select_date: false
    })
    this.loadHistoryData();
    lineChart.updateData();
  },

  //通过QueryDevicePropertiesData API读取物联网平台数据
  loadHistoryData: function () {
    var that = this;
    if (this.data.date == "1小时") {
      var startTime = Date.parse(new Date()) - 3600 * 1000;
      var endTime = Date.parse(new Date());
    }
    if (this.data.date == "1天") {
      var startTime = Date.parse(new Date()) - 24 * 3600 * 1000;
      var endTime = Date.parse(new Date());
    }
    // 3600 * 1000
    console.log(time.formatTimeTwo(startTime, 'Y/M/D h:m:s'))
    console.log(time.formatTimeTwo(endTime, 'Y/M/D h:m:s'))
    aliSdk.request({
        Action: "QueryDevicePropertiesData",
        ProductKey: app.globalData.productKey,
        DeviceName: app.globalData.deviceName,
        StartTime: endTime,
        EndTime: startTime,
        Identifier: ["temperature", "humidity", "lightLux"],
        PageSize: 10,
        Asc: 0
      }, {
        method: "POST"
      },
      (res) => {
        console.log("success")
        //光照值
        var lightJson = JSON.stringify(res.data.PropertyDataInfos.PropertyDataInfo[0].List)
        var light_json = JSON.parse(lightJson);
        var arr = light_json.PropertyInfo;
        console.log(arr[0].Time)
        for (var i = 0, len = arr.length; i < len; i++) {
          that.data.light_list[i] = arr[i].Value
          that.data.time_list[i] = time.formatTimeTwo(arr[i].Time, 'Y/M/D h:m:s')
        }
        console.log(that.data.time_list)

        //温度
        var wenduJson = JSON.stringify(res.data.PropertyDataInfos.PropertyDataInfo[1].List)
        var wendu_json = JSON.parse(wenduJson);
        var arr = wendu_json.PropertyInfo;
        for (var i = 0, len = arr.length; i < len; i++) {
          console.log(arr[i].Value); //遍历输出
          that.data.wendu_list[i] = arr[i].Value
        }
        //湿度
        var shiduJson = JSON.stringify(res.data.PropertyDataInfos.PropertyDataInfo[2].List)
        var shidu_json = JSON.parse(shiduJson);
        var arr = shidu_json.PropertyInfo;
        for (var i = 0, len = arr.length; i < len; i++) {
          that.data.shidu_list[i] = arr[i].Value
        }
        if (res.data.Code) {
          console.log(res.data.ErrorMessage)
          wx.showToast({
            title: '设备连接失败',
            icon: 'none',
            duration: 1000,
            complete: () => {}
          })
          that.setPropertyData(null)
        } else {}
      },
      (res) => {
        console.log("fail")
        wx.showToast({
          title: '网络连接失败',
          icon: 'none',
          duration: 1000,
          complete: () => {}
        })
      },
      (res) => {
        console.log("complete")
      })
  },

  //图表点击事件
  touchcanvas: function (e) {
    lineChart.showToolTip(e, {
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  //折线图绘制方法
  OnWxChart: function (x_data, y_data, name) {
    var windowWidth = '',
      windowHeight = ''; //定义宽高
    try {
      var res = wx.getSystemInfoSync(); 
      windowWidth = res.windowWidth / 750 * 690; 
      windowHeight = res.windowWidth / 750 * 550 
    } catch (e) {
      console.error('getSystemInfoSync failed!'); //如果获取失败
    }
    lineChart = new wxCharts({
      canvasId: 'lineCanvas', //输入wxml中canvas的id
      type: 'line',
      categories: x_data, //模拟的x轴横坐标参数
      animation: false, //是否开启动画
      series: [{
        name: name,
        data: y_data,
        format: function (val, name) {
          return val;
        }
      }],
      xAxis: { //是否隐藏x轴分割线
        disableGrid: true,
      },
      yAxis: { //y轴数据
        title: '', //标题
        format: function (val) { //返回数值
          return val.toFixed(2);
        },
        min: 0, //最小值
        gridColor: '#D8D8D8',
      },
      width: windowWidth * 1.1, //图表展示内容宽度
      height: windowHeight, //图表展示内容高度
      dataLabel: true, //是否在图表上直接显示数据
      dataPointShape: true, //是否在图标上显示数据点标志
      extra: {
        lineStyle: 'Broken' //曲线
      },
    });
  },
})